<?php

namespace Drupal\shushengyuan\Schemas;

use Drupal\shusy_sign\Entity\ShusySign;
use EntityFieldQuery;

class CalendarWrapper extends AbstractBaseModel {

  protected function getEntityType() {
    return FALSE;
  }

  protected function setValue() {
    [$uid] = $this->context;

    $in_month = format_date(REQUEST_TIME, 'custom', 'Y-m-d');
    $start = strtotime("first day of $in_month 00:00");
    $end = strtotime("first day of +1 month $in_month 00:00");
    $uid = $this->getUid();

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'shusy_sign');
    $query->propertyCondition('uid', $uid);
    $query->propertyCondition('created', $start, '>=');
    $query->propertyCondition('created', $end, '<');
    $query->propertyOrderBy('created');

    $result = $query->execute();
    //占位类型 0 空白占位 1 正常数据 2 日期占位
    $signs = [];
    if (!empty($result)) {
      foreach ($result['shusy_sign'] as $item) {
        $entity = shusy_sign_load($item->id);
        if ($entity instanceof ShusySign) {
          $day = format_date($entity->created, 'custom', 'Ymd');
          $signs[$day] = SignItem::init(FALSE, FALSE, [1, $entity->created]);
        }
      }
    }

    $list = [];

    /**
     * N  ISO-8601 格式数字表示的星期中的第几天（PHP 5.1.0 新加）  1（表示星期一）到 7（表示星期天）
     * w  星期中的第几天，数字表示  0（表示星期天）到 6（表示星期六）
     */
    //计算前置补充天数
    $inWeek = format_date($start, 'custom', 'N');
    for ($i = 0; $i < ($inWeek - 1); $i++) {
      $list[] = SignItem::get(FALSE, FALSE, [0, 0]);
    }

    $total_sign = 0;
    for ($i = $start; $i < $end; $i = $i + 24 * 60 * 60) {
      $iDay = format_date($i, 'custom', 'Ymd');
      if (isset($signs[$iDay])) {
        $list[] = $signs[$iDay];
        $total_sign++;
      }
      else {
        if ($i <= REQUEST_TIME) {
          $total_sign = 0;
        }
        $list[] = SignItem::get(FALSE, FALSE, [2, $i]);
      }
    }

    $groups = [];
    $i = 0;
    $group = 0;
    $items = [];
    foreach ($list as $item) {
      $i++;
      if ($i % 7 === 1 && $i > 1) {
        $group++;
        $groups[$group] = [
          'items' => $items,
        ];
        $items = [];
      }
      $items[] = [
        //0 占位 1 已签到 2 未签到
        'type' => $item['placeholder'],
        'day' => $item['day'],
      ];
    }
    if (!empty($items)) {
      $groups[$group + 1] = [
        'items' => $items,
      ];
    }

    $value = [
      'date' => $this->formatDate(REQUEST_TIME, 'Y-m'),
      'header' => [
        [
          'name' => '一',
        ],
        [
          'name' => '二',
        ],
        [
          'name' => '三',
        ],
        [
          'name' => '四',
        ],
        [
          'name' => '五',
        ],
        [
          'name' => '六',
        ],
        [
          'name' => '日',
        ],
      ],
      'groups' => array_values($groups),
      $list,
      $inWeek,
    ];
    $this->merge($value);
  }

  protected function getGroups() {

  }
}
